package org.lcc.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.lcc.model.entity.Question;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelQuestionExtractor {

    public static List<Question> extractQuestionsFromExcel(InputStream inputStream) throws IOException {
        List<Question> questions = new ArrayList<>();
        try (Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            int headerRowNum = 0; // 假设第一行为表头

            // 找到表头行中“答案”列的索引
            Row headerRow = sheet.getRow(headerRowNum);
            int answerColumnIndex = -1;
            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                System.out.println(cell.getStringCellValue());
                if (cell != null && "答案".equals(getCellValue(cell).trim())) {
                    answerColumnIndex = i;
                    break;
                }
            }

            // 如果没有找到“答案”列，抛出异常
            if (answerColumnIndex == -1) {
                throw new IllegalArgumentException("未找到“答案”列");
            }

            // 遍历数据行
            for (Row row : sheet) {
                if (row.getRowNum() == headerRowNum) {
                    continue; // 跳过表头行
                }

                Question question = new Question();
                int cellNum = 0;

                // 题型
                Cell typeCell = row.getCell(cellNum++);
                String type = typeCell != null ? getCellValue(typeCell) : null;

                // 试题内容
                Cell contentCell = row.getCell(cellNum++);
                String content = contentCell != null ? getCellValue(contentCell) : null;

                // 如果题型或试题内容为空，跳过当前行
                if (type == null || type.isEmpty() || content == null || content.isEmpty()) {
                    continue;
                }

                question.setType(type);
                question.setContent(content);

                // 动态读取选项列（从当前列到“答案”列前一列）
                List<String> options = new ArrayList<>();
                for (int i = cellNum; i < answerColumnIndex; i++) {
                    Cell optionCell = row.getCell(i);
                    options.add(optionCell != null ? getCellValue(optionCell) : "");
                }
                question.setOptions(options);
                cellNum = answerColumnIndex; // 更新列索引到“答案”列

                // 答案
                Cell answerCell = row.getCell(cellNum++);
                System.out.println(cellNum);
                question.setAnswer(answerCell != null ? getCellValue(answerCell) : "");

                //章节
                Cell subjectCell = row.getCell(cellNum++);
                System.out.println("章节"+cellNum);
                question.setSubject(subjectCell != null ? getCellValue(subjectCell) : "");


                // 难度
                Cell difficultyCell = row.getCell(cellNum++);
                question.setDifficulty(difficultyCell != null ? getCellValue(difficultyCell) : "");

                // 解析
                Cell explanationCell = row.getCell(cellNum++);
                question.setAnalysis(explanationCell != null ? getCellValue(explanationCell) : "");

                // 处理填空题的多个答案
                if ("填空题".equals(question.getType())) {
                    String answer = question.getAnswer();
                    if (answer != null && !answer.isEmpty()) {
                        String[] answers = answer.split("\\|");
                        question.setAnswer(String.join("|", answers));
                    }
                }

                // 添加到结果列表
                questions.add(question);
            }
        }
        return questions;
    }

    private static String getCellValue(Cell cell) {
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }
}